package cz.zcu.fav.ratdroid.service;

import org.apache.http.impl.client.DefaultHttpClient;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.convert.AnnotationStrategy;
import org.simpleframework.xml.core.Persister;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.xml.SimpleXmlHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import cz.zcu.fav.ratdroid.activity.SettingsActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class RestTaskFactory
{

	private static RestTemplate restTemplate;
	public static String REST_COOKIE_KEY = "JSESSIONID";

	public static <T> RestTask<T> getRestTask(String url,
			Context context, Class<T> type, IRestListener<T> listener,
			HttpMethod httpMethod)
	{
		if (restTemplate == null)
		{
			initRest(context);
		}
		RestTask<T> restTask = new RestTask<T>(context,
				restTemplate, type, listener, httpMethod);
		restTask.execute(url);
		return restTask;
	}

	public static void clear()
	{
		restTemplate = null;
	}

	public static <T> RestTask<T> getRestTask(String url,
			Context context, Class<T> type, IRestListener<T> listener,
			HttpMethod httpMethod, T body)
	{
		if (restTemplate == null)
		{
			initRest(context);
		}
		RestTask<T> restTask = new RestTask<T>(context,
				restTemplate, type, listener, httpMethod, body);
		restTask.execute(url);
		return restTask;
	}

	private static void initRest(Context context)
	{
		restTemplate = new RestTemplate();
		DefaultHttpClient client = new MyHttpClient(context);
		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
				client);
		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(context);

		// (60 * 1000) -> same as HttpComponentsClientHttpRequestFactory default
		// value
		factory.setConnectTimeout(Integer.parseInt(pref.getString(
				SettingsActivity.KEY_PREF_TIMEOUT, "" + (60 * 1000))));
		restTemplate.setRequestFactory(factory);

		// annotation strategy is used here because we need to enable @Convert
		// annotation for custom
		// data types (like joda time)
		AnnotationStrategy strategy = new AnnotationStrategy();
		Serializer serializer = new Persister(strategy);
		SimpleXmlHttpMessageConverter converter = new SimpleXmlHttpMessageConverter(
				serializer);
		restTemplate.getMessageConverters().add(converter);
	}

}
